package com.yjr.gulimall.product.service.impl;

import com.yjr.gulimall.product.entity.SkuImagesEntity;
import com.yjr.gulimall.product.entity.SpuInfoDescEntity;
import com.yjr.gulimall.product.entity.SpuInfoEntity;
import com.yjr.gulimall.product.service.*;
import com.yjr.gulimall.product.vo.SkuItemSaleAttrVo;
import com.yjr.gulimall.product.vo.SkuItemVo;
import com.yjr.gulimall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjr.common.utils.PageUtils;
import com.yjr.common.utils.Query;

import com.yjr.gulimall.product.dao.SkuInfoDao;
import com.yjr.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {

        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SkuInfoEntity> skuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            skuInfoEntityQueryWrapper.and(queryWrapper -> queryWrapper.eq("sku_id",key).or().like("sku_name",key));
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            skuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId)&& !"0".equalsIgnoreCase(catelogId)){
            skuInfoEntityQueryWrapper.eq("catalog_id",catelogId);
        }
        String min = (String)params.get("min");
        if(!StringUtils.isEmpty(min)){
            // gt : 大于;  ge: 大于等于
            skuInfoEntityQueryWrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(max)){

            try {
                BigDecimal  bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(new BigDecimal(0))==1){
                    skuInfoEntityQueryWrapper.le("price", max);
                }
            } catch (Exception e) {
                System.out.println("com.yjr.gulimall.product.service.impl.SkuInfoServiceImpl：前端传来非数字字符");
                e.printStackTrace();
            }

        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                skuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> listBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        return this.list(queryWrapper);
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> future = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息的获取  pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);

        //单独开一个线程给第二步,因为没啥关联关系
        CompletableFuture<Void> imgageFuture = CompletableFuture.runAsync(() -> {
            //2、sku的图片信息    pms_sku_images
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntities);
        }, executor);
        //等待第一步完成.....
        CompletableFuture<Void> descFuture = future.thenAcceptAsync((res) -> {
            //4、获取spu的介绍    pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> saleAttrFuture = future.thenAcceptAsync((res) -> {
            //3、获取spu的销售属性组合
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(skuItemSaleAttrVos);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = future.thenAcceptAsync((res) -> {
            //5 获取spu规格参数信息
            List<SpuItemAttrGroupVo> spuItemAttrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());

            skuItemVo.setGroupAttrs(spuItemAttrGroupVos);
        });



        // 等待所有任务都完成再返回
        CompletableFuture.allOf(imgageFuture,saleAttrFuture,descFuture,baseAttrFuture).get();
        return skuItemVo;
    }

}